package com.ljc.cjgl.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ljc.cjgl.entitiy.ClassActitvity;
import com.ljc.cjgl.entitiy.TbClass;
import com.ljc.cjgl.form.ClassActivityForm;
import com.ljc.cjgl.repository.ClassActivityRepository;

@Service
public class ClassActivityService {
	@Autowired
	ClassActivityRepository activityDAO;
	
	public ClassActitvity findById(Integer id) {
		Optional<ClassActitvity> optional = activityDAO.findById(id);
		if(optional.isPresent()) {
			return optional.get();
		}
		return null;
	}
	
	public List<ClassActitvity> findAll(){
		return activityDAO.findAll();
	}
	
	public Page<ClassActitvity> findAll(Specification<ClassActitvity> specification,Pageable pageable){
		return activityDAO.findAll(specification, pageable);
	}

	@Transactional
	public synchronized void save(ClassActivityForm form) {
		ClassActitvity model=new ClassActitvity();
		Integer id = form.getId();
		if(id!=null) {
			model=findById(id);
		}
		if(form.getClassId()!=null) {
			model.setTbClass(new TbClass(form.getClassId()));
		}
		BeanUtils.copyProperties(form, model,"tbClass","id");
		activityDAO.save(model);
	}

	@Transactional
	public synchronized boolean delete(List<ClassActitvity> actitvities) {
		try {
			for (ClassActitvity actitvity : actitvities) {
				activityDAO.deleteById(actitvity.getId());
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public List<ClassActitvity> findByTbClassId(Integer classId) {
		return activityDAO.findByTbClassId(classId);
	}
	
	
	public Page<ClassActitvity> findAll(Pageable pageable){
		return activityDAO.findAll(pageable);
	}

	public List<TbClass> findTbClass() {
		return activityDAO.findTbClass();
	}
}
